package com.app.babygo.help;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RequestHelper {

	public static void sendRequest(final String request, final String args) {
	   Thread t = new Thread(new Runnable() {
	       public void run() { 
	    	   sendHTTPRequestHelper(request, args);
	       };
	   });
	   t.start();		
	}
	
	private static void sendHTTPRequestHelper(String request, String params) {
		try {
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter outStream = new OutputStreamWriter(connection.getOutputStream());
			outStream.write(params);
			outStream.flush();
			outStream.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			while (true) {  
				String line = reader.readLine();
				if (line == null) {
					break;
				}
				result += line;   
			}
			//TODO: use JSON instead of string, and do JSON parse here!
			// json = JSON.parse(result);
			// ...
			//TODO: return this result via call back function
		} catch (MalformedURLException e) {
			//TODO: log exception or pop up a message
			//log.writeln("Error: "+e);
		} catch (IOException e) {
			//TODO: log exception or pop up a message
			//log.writeln("Error: "+e);
		} catch (Exception e) {
			//TODO: log exception or pop up a message
			//log.writeln("Unhandled Error: "+e);
		}
	}
}
